package com.galleryviewpager.i_bezier;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

import androidx.annotation.Nullable;

/**
 * 二阶贝塞尔曲线
 */
public class TwoBezierCurveView extends View {

    private Paint mPaint;
    private int mWidth, mHeight;

    private Path mPath = new Path();

    private int controlX, controlY;

    public TwoBezierCurveView(Context context) {
        this(context, null);
    }

    public TwoBezierCurveView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public TwoBezierCurveView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initPaint();
    }

    private void initPaint() {
        mPaint = new Paint();
        mPaint.setColor(Color.RED);
        mPaint.setAntiAlias(true);
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setStrokeWidth(10f);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        mWidth = widthMode == MeasureSpec.EXACTLY ? MeasureSpec.getSize(widthMeasureSpec) : 400;

        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        mHeight = heightMode == MeasureSpec.EXACTLY ? MeasureSpec.getSize(heightMeasureSpec) : 400;

        setMeasuredDimension(mWidth, mHeight);

        controlX = mWidth / 2;
        controlY = mHeight / 4;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        mPath.reset();
        int centerY = mHeight / 2;
        int startX = mWidth / 4;
        int startY = centerY;
        int endX = mWidth / 4 * 3;
        int endY = centerY;
        canvas.drawCircle(startX, startY, 10f, mPaint);
        canvas.drawCircle(controlX, controlY, 10f, mPaint);
        canvas.drawCircle(endX, endY, 10f, mPaint);

        canvas.drawLine(startX, startY, controlX, controlY, mPaint);
        canvas.drawLine(controlX, controlY, endX, endY, mPaint);
        mPath.moveTo(startX, startY);
        mPath.quadTo(controlX, controlY, endX, endY);
        canvas.drawPath(mPath, mPaint);

    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
            case MotionEvent.ACTION_MOVE:
                controlX = (int) event.getX();
                controlY = (int) event.getY();
                postInvalidate();
                break;
        }
        return super.onTouchEvent(event);
    }
}
